import { ref, computed } from "vue";
import { defineStore } from "pinia";
import {
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import { getInfo, getLogin, type Info, type LoginParams } from "@/api/user";
import { useMultiTagsStoreHook } from "./multiTags";
import { type DataInfo, setToken, removeToken, userKey } from "@/utils/auth";

export const useUserStore = defineStore("pure-user", () => {
  // State
  const info = ref<Info>();
  const roles = ref(storageLocal().getItem<DataInfo>(userKey)?.roles ?? []);

  // Getters (if needed, computed properties)
  const userRoles = computed(() => roles.value);
  const username = computed(() => info.value?.realName);
  // Actions
  const setRoles = (newRoles: Array<string>) => {
    roles.value = newRoles;
  };

  // 登陆
  const loginByUsername = async (data: LoginParams) => {
    return new Promise((resolve, reject) => {
      getLogin(data)
        .then(data => {
          if (data.code === 0) {
            setToken(data.data);
            resolve(data);
          } else {
            reject(data.message);
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  };

  // 获取用户信息
  const getUserInfo = async () => {
    const res = await getInfo();
    if (res.code === 0) {
      info.value = res.data;
    }
  };

  // 退出
  const logOut = () => {
    roles.value = [];
    removeToken();
    useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
    resetRouter();
    router.push("/login");
  };

  return {
    // State
    roles,
    username,
    info,
    // Getter
    userRoles,

    // Actions
    getUserInfo,
    setRoles,
    loginByUsername,
    logOut
  };
});

export const useUserStoreHook = () => useUserStore(store);
